<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="漏耗类型" prop="leakageType">
        <el-select v-model="queryParams.leakageType" placeholder="请选择漏耗类型" clearable>
          <el-option label="类型1" value="1"></el-option>
          <!-- 可根据实际业务扩展更多类型选项 -->
        </el-select>
      </el-form-item>
      <el-form-item label="分析日期" prop="analyseDate">
        <el-date-picker
            clearable
            v-model="queryParams.analyseDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择分析日期"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="已处理" value="1"></el-option>
          <el-option label="未处理" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['water:Leakage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['water:Leakage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['water:Leakage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['water:Leakage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="leakageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="漏耗类型" align="center" prop="leakageType">
        <template #default="scope">
          <span>{{ scope.row.leakageType === 1 ? '一级漏耗' : '其他' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="漏耗值" align="center" prop="leakageValue" />
      <el-table-column label="漏耗百分比" align="center" prop="leakagePercent" />
      <el-table-column label="分析日期" align="center" prop="analyseDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.analyseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '已处理' : '未处理' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="记录时间" align="center" prop="recordDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['water:Leakage:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['water:Leakage:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="leakageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="漏耗类型" prop="leakageType">
          <el-select v-model="form.leakageType" placeholder="请选择漏耗类型">
            <el-option label="类型1" value="1"></el-option>
            <!-- 可扩展其他类型 -->
          </el-select>
        </el-form-item>
        <el-form-item label="漏耗值" prop="leakageValue">
          <el-input v-model.number="form.leakageValue" placeholder="请输入漏耗值" />
        </el-form-item>
        <el-form-item label="漏耗百分比" prop="leakagePercent">
          <el-input v-model.number="form.leakagePercent" placeholder="请输入漏耗百分比" />
        </el-form-item>
        <el-form-item label="分析日期" prop="analyseDate">
          <el-date-picker
              clearable
              v-model="form.analyseDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择分析日期"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-value="1" inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Leakage">
import { listLeakage, getLeakage, delLeakage, addLeakage, updateLeakage } from "@/api/water/Leakage";
import { getCurrentInstance, ref, reactive, toRefs } from "vue";
// 1. 导入路由钩子，用于获取query参数
import { useRoute } from "vue-router";

const { proxy } = getCurrentInstance();
// 2. 创建路由实例，获取URL参数
const route = useRoute();

// 响应式数据：表格列表、弹窗状态、加载状态等
const leakageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 表单与查询参数的响应式封装
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    leakageType: null,
    analyseDate: null, // 分析日期查询参数
    status: null,
  },
  rules: {
    leakageType: [
      { required: true, message: "漏耗类型不能为空", trigger: "change" },
    ],
    leakageValue: [
      { required: true, message: "漏耗值不能为空", trigger: "blur" },
      { type: "number", message: "请输入有效数值", trigger: "blur" },
    ],
    leakagePercent: [
      { required: true, message: "漏耗百分比不能为空", trigger: "blur" },
      { type: "number", message: "请输入有效数值", trigger: "blur" },
    ],
    analyseDate: [
      { required: true, message: "分析日期不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询漏耗列表 */
function getList() {
  loading.value = true;
  listLeakage(queryParams.value).then((response) => {
    leakageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消弹窗
function cancel() {
  open.value = false;
  reset();
}

// 重置表单
function reset() {
  form.value = {
    id: null,
    leakageType: 1, // 表结构默认值为1
    leakageValue: null,
    leakagePercent: null,
    analyseDate: null,
    status: 0, // 表结构默认值为0
    recordDate: null,
  };
  proxy.resetForm("leakageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置查询表单 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据（用于批量操作）
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加漏耗记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getLeakage(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改漏耗记录";
  });
}

/** 提交表单（新增/修改） */
function submitForm() {
  proxy.$refs["leakageRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateLeakage(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLeakage(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm(`是否确认删除漏耗记录编号为"${_ids}"的数据项？`).then(() => {
    return delLeakage(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("water/Leakage/export", {
    ...queryParams.value,
  }, `Leakage_${new Date().getTime()}.xlsx`);
}

// 3. 新增：初始化时获取query参数并自动搜索
function initQueryParams() {
  // 从URL中获取"analyseDate"参数（与页面分析日期字段对应）
  const targetDate = route.query.analyseDate;

  // 若存在日期参数，设置到查询条件并自动搜索
  if (targetDate) {
    queryParams.value.analyseDate = targetDate; // 填充到日期选择器
    handleQuery(); // 自动执行搜索
  } else {
    // 若无参数，执行默认查询（保持原有逻辑）
    getList();
  }
}

// 页面挂载时执行初始化
onMounted(() => {
  initQueryParams(); // 此时路由参数已同步，可正常获取
});

</script>